class Bluetooth {

	constructor() {
		// 是否初始化成功
		this.isOpenBle = false;
		// 缓存的key值
		this.deviceTitle = 'deviceInfo';
		// 蓝牙设备信息
		this.deviceInfo = {
			name: '',
			deviceId: '',
			serviceId: '',
			characteristicId: ''
		};
	}
	// 消息弹窗
	showToast(title) {
		uni.showToast({
			title: title,
			icon: 'none',
			'duration': 2000
		});
	};
	// 初始化蓝牙模块
	openBluetoothAdapter() {
		return new Promise((resolve, reject) => {
			uni.openBluetoothAdapter({
				success: res => {
					this.isOpenBle = true;
					resolve(res);
				},
				fail: err => {
					this.showToast('请检查是否已开启蓝牙');
					reject(err);
				},
			});
		});
	};
	// 初始化蓝牙模块
	openBluetoothAdapterByMol(callback) {
		return new Promise((resolve, reject) => {
			uni.openBluetoothAdapter({
				success: res => {
					this.isOpenBle = true;
					if(callback&&callback.success)
					{
						callback.success(res);
					}
					else
					{
					resolve(res);
					}
				},
				fail: err => {
					this.showToast('请检查是否已开启蓝牙');
					if(callback&&callback.fail)
					{
						callback.fail(err);
					}
					else
					{
					reject(err);
					}
					
				},
			});
		});
	};
	// 监听蓝牙适配器状态变化事件
	onBluetoothAdapterStateChange() {
		uni.onBluetoothAdapterStateChange(function(res) {
			console.log('adapterState changed, now is', res)
		})
	};
	// 停止搜寻附近的蓝牙外围设备
	stopBluetoothDevicesDiscovery() {
		let _this = this;
		return new Promise((resolve, reject) => {
			uni.stopBluetoothDevicesDiscovery({
				success: res => {
					uni.hideLoading();
				},
				fail: err => {
					uni.hideLoading();
					_this.showToast(`停止搜索蓝牙设备失败` + JSON.stringify(err));
				}
			})
		});
	}
	// 连接蓝牙设备
	createBLEConnection() {
		//设备deviceId
		let deviceId = this.deviceInfo.deviceId;

		uni.showLoading({
			mask: true,
			title: '蓝牙连接中'
		})

		return new Promise((resolve, reject) => {
			uni.createBLEConnection({
				deviceId,
				timeout: 10000,
				success: res => {
					resolve(res)
				},
				fail: err => {
					console.log(err, 7489748949);
					uni.hideLoading();
					reject(err);
				}
			})
		});
	}
	// 获取蓝牙设备所有服务(service)
	getBLEDeviceServices() {
		let _serviceList = [];
		let deviceId = this.deviceInfo.deviceId;

		return new Promise((resolve, reject) => {
			setTimeout(() => {
				uni.getBLEDeviceServices({
					deviceId,
					success: res => {
						for (let service of res.services) {
							if (service.isPrimary) {
								_serviceList.push(service);
							}
						}
						uni.hideLoading();
						resolve(_serviceList)
					},
					fail: err => {
						uni.hideLoading();
						reject(err);
					},
				})
			}, 500);
		});
	};
	// 获取蓝牙设备某个服务中所有特征值(characteristic)
	getBLEDeviceCharacteristics() {
		const _this = this;
		const {
			deviceId,
			serviceId
		} = _this.deviceInfo;

		return new Promise((resolve, reject) => {
			uni.getBLEDeviceCharacteristics({
				deviceId,
				serviceId,
				success: res => {
					for (let _obj of res.characteristics) {
						// 该特征值是否支持 write 操作
						if (_obj.properties.write) {
							_this.deviceInfo.characteristicId = _obj.uuid;
							uni.setStorageSync(_this.deviceTitle, _this.deviceInfo);
						}
					}

					let result = {
						'characteristicId': _this.deviceInfo.writeId
					};
					resolve(result)
				},
				fail: err => {
					reject(err);
				}
			})
		});
	};
	// 断开联链接
	closeBLEConnection() {
		let deviceId = this.deviceInfo.deviceId;
		return new Promise((resolve, reject) => {
			uni.closeBLEConnection({
				deviceId,
				success: res => {
					resolve(res);
					console.log(res, '断开连接')
				},
				fail: err => {
					console.log(err, '失败')
					reject(err);
				}
			})
		});
	}
	// 向低功耗蓝牙设备特征值中写入二进制数据
	writeBLECharacteristicValue(buffer) {
		const {
			deviceId,
			serviceId,
			characteristicId
		} = this.deviceInfo;

		return new Promise((resolve, reject) => {
			uni.writeBLECharacteristicValue({
				deviceId,
				serviceId,
				characteristicId,
				value: buffer,
				success: res => {
					console.log('message发送成功', JSON.stringify(res));
					resolve(res);
				},
				fail: err => {
					if (err.errCode === 10001) {
						this.showToast('请检查是否已开启蓝牙');
					}
					if (err.errCode === 10006) {
						this.showToast('连接已断开, 请检查设备后重新连接');
					}
					console.log('message发送失败', JSON.stringify(err));
					reject(err);
				}
			});
		});
	}
	// 关闭蓝牙模块。调用该方法将断开所有已建立的连接并释放系统资源
	closeBluetoothAdapter() {
		uni.closeBluetoothAdapter({
			success: res => {
				console.log(res)
			}
		});
	}
	//若APP在之前已有搜索过某个蓝牙设备，并成功建立连接，可直接传入之前搜索获取的 deviceId 直接尝试连接该设备，无需进行搜索操作。
	reconnect() {
		(async () => {
			try {
				this.deviceInfo = uni.getStorageSync(this.deviceTitle);

				let result1 = await this.createBLEConnection();
				console.log("createBLEConnection: " + JSON.stringify(result1));

				let result2 = await this.getBLEDeviceServices();
				console.log("getBLEDeviceServices: " + JSON.stringify(result2));

				let result3 = await this.getBLEDeviceCharacteristics();
				console.log("getBLEDeviceCharacteristics: " + JSON.stringify(result3));

				// this.writeId = uni.getStorageSync("writeId");
				// this.notifyId = uni.getStorageSync("notifyId");
			} catch (err) {
				console.log("err: " + JSON.stringify(err));
			}

		})();
	}
}

export default Bluetooth;